package tk.heimashuma.store.annotation;

import org.apache.http.HttpResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.Optional;
public class JsonReturnHandler implements HandlerMethodReturnValueHandler {
    @Override
    public boolean supportsReturnType(MethodParameter methodParameter) {
        // 判断当前方法上是否有@JSON主键
        boolean hasJsonAnnotation = Optional.ofNullable(methodParameter.getMethodAnnotation(JSON.class)).isPresent();
        return hasJsonAnnotation;
    }

    @Override
    public void handleReturnValue(Object o, MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest) throws Exception {

        // 设置最终处理类
        modelAndViewContainer.setRequestHandled(false);
        // 获取处理的响应信息
        HttpServletResponse nativeResponse = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        // 获取注解的参数
        Annotation[] methodAnnotations = methodParameter.getMethodAnnotations();
        CustomerJsonSerializer jsonSerializer = new CustomerJsonSerializer();
        Arrays.asList(methodAnnotations).forEach(a -> {
            if(a instanceof JSON){
                JSON json = (JSON) a;
                jsonSerializer.filter(json.type(),json.include(),json.filter());
            }
        });

        nativeResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        String json = jsonSerializer.toJson(o);
        nativeResponse.getWriter().write(json);
    }
}
